﻿using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace WPFExcelReport
{
    public partial class SDBASE : ViewBase
    {
        #region ==V1===========
        public static readonly DependencyProperty V1Property = DependencyProperty.Register("V1",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("00", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnV1Changed));
        public string V1
        {
            get
            {
                return (string)GetValue(V1Property);
            }
            set
            {
                SetValue(V1Property, value);
                OnV1Chg();
            }
        }

        private static void OnV1Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.V1 = (string)e.NewValue;
            }
        }

        public virtual void OnV1Chg()
        {
        }

        #endregion
        #region ==IsV1===========
        public static readonly DependencyProperty IsV1Property = DependencyProperty.Register("IsV1",
            typeof(bool), typeof(SDBASE),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsV1Changed));
        public bool IsV1
        {
            get
            {
                return (bool)GetValue(IsV1Property);
            }
            set
            {
                SetValue(IsV1Property, value);
            }
        }
        private static void OnIsV1Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.IsV1 = (bool)e.NewValue;
            }
        }
        #endregion
        public VSDDAT TMV
        {
            get
            {
                return (VSDDAT)MV;
            }
        }
        #region ==LMS===========
        public static readonly DependencyProperty LMSProperty = DependencyProperty.Register("LMS",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnLMSChanged));
        public string LMS
        {
            get
            {
                return (string)GetValue(LMSProperty);
            }
            set
            {
                SetValue(LMSProperty, value);
            }
        }
        private static void OnLMSChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.LMS = (string)e.NewValue;
            }
        }
        #endregion

        #region ==KEYS===========
        public static readonly DependencyProperty KEYSProperty = DependencyProperty.Register("KEYS",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnKEYSChanged));
        public string KEYS
        {
            get
            {
                return (string)GetValue(KEYSProperty);
            }
            set
            {
                SetValue(KEYSProperty, value);
            }
        }
        private static void OnKEYSChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.KEYS = (string)e.NewValue;
            }
        }
        #endregion

        #region ==SDSA===========
        public static readonly DependencyProperty SDSAProperty = DependencyProperty.Register("SDSA",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSDSAChanged));
        public string SDSA
        {
            get
            {
                return (string)GetValue(SDSAProperty);
            }
            set
            {
                SetValue(SDSAProperty, value);
                OnSDSAChg();
            }
        }
        private static void OnSDSAChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.SDSA = (string)e.NewValue;
            }
        }
        public virtual void OnSDSAChg()
        {

        }
        #endregion

        #region ==SDES===========
        public static readonly DependencyProperty SDESProperty = DependencyProperty.Register("SDES",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSDESChanged));
        public string SDES
        {
            get
            {
                return (string)GetValue(SDESProperty);
            }
            set
            {
                SetValue(SDESProperty, value);
            }
        }
        private static void OnSDESChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.SDES = (string)e.NewValue;
            }
        }
        #endregion

        #region ==dwKEY===========
        public static readonly DependencyProperty dwKEYProperty = DependencyProperty.Register("dwKEY",
            typeof(DataRow), typeof(SDBASE),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OndwKEYChanged));
        public DataRow dwKEY
        {
            get
            {
                return (DataRow)GetValue(dwKEYProperty);
            }
            set
            {
                SetValue(dwKEYProperty, value);
            }
        }
        private static void OndwKEYChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.dwKEY = (DataRow)e.NewValue;
            }
        }
        #endregion

        #region ==VALUE===========
        public static readonly DependencyProperty VALUEProperty = DependencyProperty.Register("VALUE",
            typeof(string), typeof(SDBASE),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnVALUEChanged));
        public string VALUE
        {
            get
            {
                return ((VSDDAT)MV).VALUE;
            }
            set
            {
                SetValue(VALUEProperty, value);
                ((VSDDAT)MV).VALUE = value;
            }
        }
        private static void OnVALUEChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.VALUE = (string)e.NewValue;
            }
        }
        #endregion

        #region ==IsCombo===========
        public static readonly DependencyProperty IsComboProperty = DependencyProperty.Register("IsCombo",
            typeof(bool), typeof(SDBASE),
            new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsComboChanged));
        public bool IsCombo
        {
            get
            {
                return (bool)GetValue(IsComboProperty);
            }
            set
            {
                SetValue(IsComboProperty, value);
            }
        }
        private static void OnIsComboChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as SDBASE;
            if (src != null)
            {
                src.IsCombo = (bool)e.NewValue;
            }
        }
        #endregion

        public SDBASE()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VSDDAT();
            DataContext = MV;
            LANG = "V";
            IsEdit = false;
        }

        public override void vwMaster_CurrentChanged(object sender, EventArgs e)
        {
            base.vwMaster_CurrentChanged(sender, e);
            dwKEY = dwMaster;
            try
            {
                if (dwKEY != null)
                {
                    KEY = dwKEY["KEY"].ToString();
                    DES = Helpers.Helper.ConvertGB2312To8859P1(dwKEY["DES"].ToString());
                    SDES = Helpers.Helper.ConvertGB2312To8859P1(dwKEY["SDES"].ToString());
                    if (TBMain.Columns.Contains("VALUE"))
                    {
                        VALUE = dwKEY["VALUE"].ToString();
                    }
                }
                else
                {

                    KEY = "";
                    DES = "";
                    SDES = "";
                    VALUE = "000000";
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public virtual void SetUp()
        {
            TMV.SetUp(SDSA);
        }
        public override void LOADALL()
        {
            if (SDSA.Trim().Length == 0)
                return;
            try
            {
                string[] keys;
                string sdkey = "";
                if (DBSDDAT.ContainsKey(SDSA))
                {
                    TBMain.Clear();
                    if (KEYS.Length == 0)
                    {
                        TBMain.Merge(DBSDDAT[SDSA].Copy());
                    }
                    else
                    {
                        keys = KEYS.Split(';');

                        foreach (string key in keys)
                        {
                            filter += "Trim(KEY)='" + key + "' OR ";
                        }
                        filter += "***";
                        filter = filter.Replace("OR ***", "");
                        rows = DBSDDAT[SDSA].Select(filter);
                        TBMain.Merge(rows.CopyToDataTable());
                    }
                    if (TBMain.Rows.Count > 0)
                    {
                        return;
                    }
                }
                int idx = SDSA.IndexOfAny(new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'K', 'R', 'V' });
                if (idx > 0)
                    return;
                SetUp();
                dwData = TBMain.NewRow();
                dwData["SDSA"] = SDSA;
                if (KEYS.Length > 0)
                {
                    keys = KEYS.Split(';');
                    sdkey = "";
                    foreach (string key in keys)
                    {
                        if (LANG.Trim() == "EN")
                        {
                            sdkey += "SDKEY='" + app.Mandant + key.PadRight(21) + "E' OR ";
                        }
                        else
                        {
                            sdkey += "SDKEY='" + app.Mandant + key.PadRight(21) + "V' OR ";
                        }

                    }
                    sdkey += "***";
                    sdkey = sdkey.Replace("OR ***", "");
                    sdkey = " AND (" + sdkey + ")";
                    dwData["SDKEY"] = sdkey;
                }
                else
                {
                    if (LANG.Trim() == "EN")
                    {
                        dwData["SDKEY"] = " AND SDKEY LIKE '%" + "E'";
                        dwData["SDKEY"] = " AND SDKEY LIKE '%" + "V'";
                    }
                    else
                    {
                        dwData["SDKEY"] = " AND SDKEY LIKE '%" + "V'";
                    }
                }
                SResult = TMV.QuerySDDAT(dwData, Convert.ToInt16(SDSA));
                MergeData(SResult, false);
                if (KEY.Length > 0)
                {
                    ORDERNUM = KEY;
                }
                DBSDDAT[SDSA] = TBMain.Copy();
            }
            catch (Exception ex)
            {

            }
        }

        public override void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            if (IsLoaded) return;
            base.Window_Loaded(sender, e);
            // LOADALL();
            //NormalTask= Task.Factory.StartNew(() => LOADALL(), new CancellationTokenSource().Token, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public override void DeleteCommand(object sender, System.Windows.RoutedEventArgs e)
        {
            if (dwMaster == null)
                return;
            foreach (var item in ((DataGrid)master).SelectedItems)
            {
                if (!item.GetType().ToString().Contains("DataRowView")) continue;
                DataRow _dwWB = ((System.Data.DataRowView)item).Row;
                TMV.DSD01(_dwWB);
            }

            TMV.DSD01(dwMaster);
            string sdkey = dwMaster["SDKEY"].ToString();
            vwMaster.View.MoveCurrentTo(-1);
            string filter = "SDKEY='" + sdkey + "'";
            DataRow[] rows = TBMain.Select(filter);
            foreach (DataRow row in rows)
            {
                row.Delete();
            }
            TBMain.AcceptChanges();
            if (vwMaster.View != null)
            {
                vwMaster.View.MoveCurrentToLast();
            }
            base.QueryCommand(sender, e);
        }
        public override void OnManageChg()
        {
            if (IsManage)
            {
                if (DBSDDAT.ContainsKey(SDSA))
                {
                    DBSDDAT.Remove(SDSA);
                }
            }
            base.OnManageChg();
        }
        public override void ManageCommand(object sender, RoutedEventArgs e)
        {
            if (IsManage)
            {
                if (DBSDDAT.ContainsKey(SDSA))
                {
                    DBSDDAT.Remove(SDSA);
                    return;
                }
                LOADALL();
            }
            else
            {
                VICC_WFEVENTS.SVWF.SD02(RUNID, SDSA);
            }
            base.ManageCommand(sender, e);
        }
        public override void LOADBYAUF()
        {
            base.LOADBYAUF();
            Locate("KEY", ORDERNUM);
        }

        public override void OnEXAUFChg(string vlaue)
        {
            Locate("KEY", EXAUF);
            base.OnEXAUFChg(vlaue);
        }
        public override void OnLANGChg(string lang)
        {
            if (!IsLoaded)
                return;
            LOADALL();
            base.OnLANGChg(lang);
        }

        public override void OnSave()
        {
            base.OnSave();
       

            try
            {
                if (!IsSaved)
                    return;
                foreach (DataRow row in TBMain.Rows)
                {
                    if (row.RowState == DataRowState.Unchanged) continue;
                    TMV.Save(row);
                } 

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}
